<?php

namespace app\devices\controller;

use app\devices\service\SocketService;
use app\wechat\service\WechatService;
use think\admin\Controller;
use think\admin\Storage;
use think\cache\driver\Redis;
use think\exception\HttpResponseException;
use WeMini\Qrcode;

/**
 * 箱柜管理
 * Class Index
 * @package app\data\controller
 */
class Feedback extends Controller
{

    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'JcgFeedback';

    protected $ranks = [1=>'正常', 2=>'紧急'];
    protected $feed_types = [1=>'售前咨询',2=>'售后问题',3=>'bug反馈',4=>'优化建议'];
    protected $replys = ['不可重现','可以重现'];
    protected $status_arr = ['未解决','解决中','已解决'];

    /**
     * 意见反馈管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '意见反馈管理';
        $map = [];

        $query = $this->_query($this->table);
        $query->like('replay_summary,content');
        $query->where($map)->order('id desc')->equal('status')->dateBetween('create_at')->page();
    }

    /**
     * 列表数据处理
     * @param $data
     */
    public function _index_page_filter(&$data){
        if($data){
            foreach ($data as &$row){
                $files = explode(",",$row['files']);
                if($files){
                    foreach ($files as &$val){
                        if($val){
                            $ext = explode(".",$val);
                            if(end($ext)=='mp4'){
                                $val = '<a class="video" data-url="'.$val.'"><i class="layui-icon layui-icon-video" style="font-size: 40px"></i></a>';
                            }else if(end($ext)=='mov'){
                                $val = '<a class="video" data-url="'.$val.'"><i class="layui-icon layui-icon-video" style="font-size: 40px"></i></a>';
                            }else{
                                $val = '<div style="width:40px; height:40px; display: inline-block; margin-right:5px;" data-tips-image data-lazy-src="'.$val.'"></div>';
                            }
                        }
                    }
                    $row['files'] = implode(" ",$files);
                }

                $row['contents'] = stripos($row['contents'],"#")?substr($row['contents'],0, stripos($row['contents'],"#")):$row['contents'];
                $row['short'] = mb_substr($row['contents'],0,10,'utf-8').'...';
            }
        }
    }

    /**
     * 编辑意见反馈
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->_form($this->table, 'form');
    }

    /**
     * 数据表单处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if($this->app->request->isPost()){
            if($data['remark']){
                $data['contents'] .= "#".$data['remark']."#，";
            }
        }else{
            $contents = str_replace(PHP_EOL,"<br/>", $data['contents']);
            $reg = "/#.*?#/";
            preg_match_all($reg, $contents, $matches);
            if($matches){
                $this->assign("reply", str_replace("#","", str_replace("<br/>",PHP_EOL,$matches[0])));
            }
            $data['all'] = $data['contents'];
            $data['contents'] = stripos($data['contents'],"#")?substr($data['contents'],0, stripos($data['contents'],"#")):$data['contents'];
        }
    }

    /**
     * 修改意见反馈状态
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:1,2'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除意见反馈
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    public function getXOR($str)
    {
        $crytxt = '';
        $str_arr = str_split($str, 2);
        $m = 0;
        for($i=0; $i<strlen($str); $i++) {
            $m++;
            if(isset($str_arr[$m])){
                $a = $crytxt?$crytxt:$str_arr[$i];
                $crytxt = chr(hexdec(($a))) ^ chr(hexdec(($str_arr[$m])));
                $crytxt = $this->bytetostr($crytxt);
            }
        }
        return $crytxt;
    }

    //字节码转16进制字符串
    public function bytetostr($str)
    {
        $arr = str_split($str, 1);
        $strs = [];
        foreach ($arr as $h) {
            $s = dechex(ord($h));
            $s = is_numeric($s)?($s<10?'0'.$s:$s):$s;
            $strs[] = $s;
        }
        return strtoupper(implode("", $strs));
    }

    public function createQrcode(){
        // 关键字二维码生成
        try {
            $wechat = WechatService::WeChatQrcode();
            $result = $wechat->create($this->request->get('keys', ''));
            $this->success('生成二维码成功！', "javascript:$.previewImage('{$wechat->url($result['ticket'])}')");
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error("生成二维码失败，请稍候再试！<br> {$exception->getMessage()}");
        }
    }

    public function createWeMiniQrcode(){
        // 关键字二维码生成
        try {
            $wxapp = sysconf();
            $app = $wxapp['data'];
            $wechat = new Qrcode(['appid'=>$app['wxapp_appid'], 'appsecret'=>$app['wxapp_appkey'], 'cache_path'=>$this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . 'wechat']);
            $d_id = $this->request->get('d_id', '');
            $result = $wechat->createMiniScene('d_id='.$d_id,'haoDa/index/index');

            $info = Storage::instance('Qiniu')->set('qr_code.png', $result);

            $url = $info['url'];

            $this->success('生成二维码成功！', "javascript:$.previewImage('{$url}')");
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $trace = json_encode($exception->getTrace(), 256);
            $this->error("生成二维码失败，请稍候再试！<br> {$exception->getMessage()} <br> {$trace}");
        }
    }
}


